package com.caltco.cargo.ops.modules.sys.config;

import com.alibaba.fastjson2.JSON;

import com.alibaba.fastjson2.TypeReference;
import com.caltco.cargo.ops.modules.sys.entity.List.Meaning;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JsonTypeHandlerMeaningList extends BaseTypeHandler<List<List<Meaning>>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<List<Meaning>> parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public List<List<Meaning>> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return jsonToList(rs.getString(columnName));
    }

    @Override
    public List<List<Meaning>> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return jsonToList(rs.getString(columnIndex));
    }

    @Override
    public List<List<Meaning>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return jsonToList(cs.getString(columnIndex));
    }

    private List<List<Meaning>> jsonToList(String json) {
        System.out.println("Parsing JSON: " + json); // 添加这行打印
        if (json == null || json.isEmpty()) {
            return new ArrayList<>();
        }
        try {
            // 解析 JSON 数据为 List<List<Meaning>>
            return JSON.parseObject(json, new TypeReference<List<List<Meaning>>>() {});
        } catch (Exception e) {
            throw new RuntimeException("JSON 解析错误: " + json, e);
        }
    }
}
